'use strict';

const Service = require('egg').Service;

/**
 * 人员项目组关系服务类
 * 处理人员和项目组之间的关联关系管理
 */
class PersonProjectGroupService extends Service {
  /**
   * 获取人员所属的所有项目组
   * 返回项目组列表及加入时间
   * @param {number} personId - 人员ID
   * @returns {Promise<Array>} 项目组列表，按加入时间降序排序
   */
  async getGroupsByPersonId(personId) {
    const sql = `
      SELECT 
        g.*,
        ppg.created_at as join_time
      FROM tb_person_project_group ppg
      LEFT JOIN tb_project_group g ON ppg.project_group_id = g.project_group_id
      WHERE ppg.person_id = ? AND g.is_deleted = 0
      ORDER BY ppg.created_at DESC
    `;
    const result = await this.app.mysql.query(sql, [personId]);
    return result;
  }

  /**
   * 获取项目组的所有成员
   * 返回成员列表及其部门信息、加入时间
   * @param {number} groupId - 项目组ID
   * @returns {Promise<Array>} 成员列表，按加入时间降序排序
   */
  async getPersonsByGroupId(groupId) {
    const sql = `
      SELECT 
        p.*,
        d.department_name,
        ppg.created_at as join_time
      FROM tb_person_project_group ppg
      LEFT JOIN tb_person p ON ppg.person_id = p.person_id
      LEFT JOIN tb_department d ON p.department_id = d.department_id
      WHERE ppg.project_group_id = ? AND p.is_deleted = 0
      ORDER BY ppg.created_at DESC
    `;
    const result = await this.app.mysql.query(sql, [groupId]);
    return result;
  }

  /**
   * 检查人员是否已在项目组中
   * @param {number} personId - 人员ID
   * @param {number} groupId - 项目组ID
   * @returns {Promise<boolean>} 是否已存在关联关系
   */
  async checkExists(personId, groupId) {
    const result = await this.app.mysql.query(
      'SELECT COUNT(*) as count FROM tb_person_project_group WHERE person_id = ? AND project_group_id = ?',
      [personId, groupId]
    );
    return result[0].count > 0;
  }

  /**
   * 添加人员到项目组
   * 自动记录加入时间
   * @param {number} personId - 人员ID
   * @param {number} groupId - 项目组ID
   * @returns {Promise<Object|{error: string}>} 添加结果，重复添加返回错误信息
   */
  async addPersonToGroup(personId, groupId) {
    // 检查是否已存在关联关系
    const exists = await this.checkExists(personId, groupId);
    if (exists) {
      return { error: 'already_exists' };
    }

    // 添加关联关系
    await this.app.mysql.insert('tb_person_project_group', {
      person_id: personId,
      project_group_id: groupId,
      created_at: this.app.mysql.literals.now,
    });

    return { success: true };
  }

  /**
   * 从项目组移除人员
   * @param {number} personId - 人员ID
   * @param {number} groupId - 项目组ID
   * @returns {Promise<Object>} 移除结果
   */
  async removePersonFromGroup(personId, groupId) {
    await this.app.mysql.delete('tb_person_project_group', {
      person_id: personId,
      project_group_id: groupId,
    });

    return { success: true };
  }
}

module.exports = PersonProjectGroupService; 